package com.zh.note.huawei.onehundred.字符串摘要;

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Scanner scanner = new Scanner(System.in);
        // String inputStr = scanner.nextLine();
        String inputStr = "bAaAcBb";

        String filteredStr = "";
        //过滤掉非字母
        for (int i = 0; i < inputStr.length(); i++) {
            char ch = inputStr.charAt(i);
            if (Character.isLetter(ch)) {
                filteredStr += ch;
            }
        }

        int count = 1; //用来记录连续字符的个数
        //获取最后一个字符，并将它变成小写
        char preChar = Character.toLowerCase(filteredStr.charAt(filteredStr.length() - 1));
        //存贮最终结果
        List<Map.Entry<Character, Integer>> charCountList = new ArrayList<>();
        //统计字符出现次数
        Map<Character, Integer> charCountMap = new HashMap<>();
        //从后往前统计
        for (int i = filteredStr.length() - 2; i >= 0; i--) {
            char ch = Character.toLowerCase(filteredStr.charAt(i));
            if (preChar == ch) {
                count++;
            } else {
                //当前正在遍历的与前一个不同时
                if (count == 1) { // 如果只有一个连续，统计次数要变成0
                    count += charCountMap.getOrDefault(preChar, 0) - 1;
                    charCountMap.put(preChar, count + 1);
                } else {
                    charCountMap.put(preChar, count);
                }
                charCountList.add(new AbstractMap.SimpleEntry<>(preChar, count));
                preChar = ch;
                count = 1;
            }
            if (i == 0) {
                if (count == 1) {
                    count += charCountMap.getOrDefault(preChar, 0) - 1;
                }
                charCountList.add(new AbstractMap.SimpleEntry<>(preChar, count));
            }
        }

        charCountList.sort((a, b) -> {
            if (a.getValue().equals(b.getValue())) {
                return a.getKey() - b.getKey();
            }
            return b.getValue() - a.getValue();
        });

        StringBuilder result = new StringBuilder();
        for (Map.Entry<Character, Integer> entry : charCountList) {
            result.append(entry.getKey()).append(entry.getValue());
        }
        System.out.println(result.toString());
    }
}

